from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.db import transaction

from artmarket.models import Comment, Rating
from artmarket.serializers import CommentSerializer, RatingSerializer, CommentAndRatingSerializer, RatingListSerializer, \
    CommentListSerializer


class CommentAndRatingListView(APIView):
    """
    列出所有评论和评级，或创建新的评论和评级。
    """

    def get(self, request):
        pass

    def post(self, request):
        serializer = CommentAndRatingSerializer(data=request.data)
        if serializer.is_valid():
            comment_and_rating = serializer.save()

            # 序列化 comment 和 rating 对象
            comment_serializer = CommentSerializer(comment_and_rating['comment'])
            rating_serializer = RatingSerializer(comment_and_rating['rating'])

            # Construct the response data
            response_data = {
                'comment': comment_serializer.data,
                'rating': rating_serializer.data
            }

            return Response(data={'results': response_data}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class CommentAndRatingDetailView(APIView):
    """
    获取，更新或删除特定的评论和评级。
    """

    def get(self, request, artwork_id):
        comments = Comment.objects.filter(artwork_id=artwork_id)
        ratings = Rating.objects.filter(artwork_id=artwork_id)

        # Serialize the comments and ratings
        comment_serializer = CommentListSerializer(comments, many=True)
        rating_serializer = RatingListSerializer(ratings, many=True)

        # Construct the response data
        response_data = {
            'comments': comment_serializer.data,
            'ratings': rating_serializer.data
        }

        return Response(response_data, status=status.HTTP_200_OK)

    def put(self, request, pk):
        pass


class CommentAndRatingDeleteView(APIView):
    def delete(self, request, comment_id, rating_id):
        try:
            comment = Comment.objects.get(pk=comment_id)
            rating = Rating.objects.get(pk=rating_id)
            comment.delete()
            rating.delete()
            return Response({'message': '评论和评分删除成功'}, status=status.HTTP_200_OK)
        except (Comment.DoesNotExist, Rating.DoesNotExist):
            return Response({'message': '评论或评分不存在'}, status=status.HTTP_400_BAD_REQUEST)
